package cc.rengu.igas.bsps.core.service.trans;

import cc.rengu.igas.bsps.common.constant.BspsAppParamConstant;
import cc.rengu.igas.bsps.common.dao.BspsDevBindInfoMapper;
import cc.rengu.igas.bsps.common.dao.BspsMchntBindInfoMapper;
import cc.rengu.igas.bsps.common.dao.BspsQrCodeInfoMapper;
import cc.rengu.igas.bsps.common.dao.BspsUserInfoMapper;
import cc.rengu.igas.bsps.common.dao.impl.BspsDevBindInfoMapperImpl;
import cc.rengu.igas.bsps.common.dao.impl.BspsMchntBindInfoMapperImpl;
import cc.rengu.igas.bsps.common.dao.impl.BspsQrCodeInfoMapperImpl;
import cc.rengu.igas.bsps.common.dao.impl.BspsUserInfoMapperImpl;
import cc.rengu.igas.bsps.common.entity.DevBindInfo;
import cc.rengu.igas.bsps.common.entity.MchntBindInfo;
import cc.rengu.igas.bsps.common.entity.QrCodeInfo;
import cc.rengu.igas.bsps.common.entity.UserInfo;
import cc.rengu.igas.bsps.common.enums.BindStatusEnum;
import cc.rengu.igas.bsps.common.enums.RespCodeEnum;
import cc.rengu.igas.bsps.core.service.base.ManageService;
import cc.rengu.igas.bsps.facade.request.MchntUnBindRequest;
import cc.rengu.igas.bsps.facade.response.MchntUnBindResponse;
import cc.rengu.oltp.service.common.constant.AppConfigConstant;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.util.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wangcheng
 * @version 1.0
 * 商户绑定关系解绑
 */
public class MchntUnBindService extends ManageService {
    @Override
    protected Object bizBeforeCust() throws Exception {
        MchntUnBindRequest mchntUnBindRequest = new MchntUnBindRequest();
        ConvertUtil.convertOutput(mchntUnBindRequest);
        return mchntUnBindRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        MchntUnBindRequest mchntUnBindRequest = (MchntUnBindRequest) request;
        MchntUnBindResponse mchntUnBindResponse = new MchntUnBindResponse();
        mchntUnBindResponse.setHeader(mchntUnBindRequest.getHeader());
        /*获取请求信息：法人行号，用户标识，商户号 */
        String instId = mchntUnBindRequest.getHeader().getInstId();
        String userId = mchntUnBindRequest.getUserId();
        String mchntNo = mchntUnBindRequest.getMchntNo();
        rglog.info("法人行:" + instId + "用户标识:" + userId + "商户号:" + mchntNo);
        if (StringUtil.isEmptyOrNull(instId) || StringUtil.isEmptyOrNull(mchntNo)) {
            rglog.error("必填性校验失败！");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }
        /* 获取商户绑定信息 */
        List<MchntBindInfo> mchntBindInfoList = new ArrayList<>();
        BspsMchntBindInfoMapper bspsMchntBindInfoMapper = new BspsMchntBindInfoMapperImpl();
        if (StringUtil.isEmptyOrNull(userId)) {
            MchntBindInfo mchntBindInfo = bspsMchntBindInfoMapper.selectBspsMchntBindInfoListByUserIdAndMchntNo(instId, userId, mchntNo);
            if (null != mchntBindInfo) {
                mchntBindInfoList.add(mchntBindInfo);
            }
        } else {
            List<MchntBindInfo> mchntBindInfos = bspsMchntBindInfoMapper.selectBspsMchntBindInfoByMchntNo(instId, mchntNo);
            if (null != mchntBindInfos && !mchntBindInfos.isEmpty()) {
                mchntBindInfoList.addAll(mchntBindInfos);
            }
        }
        if (mchntBindInfoList.isEmpty()) {
            rglog.debug("没有需要解绑的商户信息,instId:<{}>,mchntNo:<{}>", instId, mchntNo);
            return new BizResponse(RespCodeEnum.TRANS_SUCCESS.getRespCode(), RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        }
        /* 开启数据库事务 */
        String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppConfigConstant.DATABASE_CONF_NODE, AppConfigConstant.OLTP_POOL_NAME);
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.OLTP_POOL_NAME);
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        dbsUtil.dbsBeginTransaction();
        /* 用户信息、商户绑定信息、设备绑定信息、二维码信息解绑处理 */
        for (MchntBindInfo mchntBindInfo : mchntBindInfoList) {
            /*0-用户表信息更新-用户表更新为解绑状态 */
            UserInfo userInfo = new UserInfo();
            userInfo.setInstId(instId);
            userInfo.setUserStatus("01");
            userInfo.setLastOprId(mchntBindInfo.getBindUserId());
            userInfo.setLastUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
            BspsUserInfoMapper bspsUserInfoMapper = new BspsUserInfoMapperImpl();
            int iReturnCode = bspsUserInfoMapper.updateBspsUserInfoByPrimaryKey(userInfo);
            if (0 != iReturnCode && BspsAppParamConstant.NODATA_CODE != iReturnCode) {
                dbsUtil.dbsEndTransaction(false);
                rglog.error("收银员解绑失败,iReturnCode:<{}>", iReturnCode);
                throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
            }
            /* 1-商户绑定信息表更新 */
            mchntBindInfo.setBindStatus(BindStatusEnum.UNBIND.getStatus());
            mchntBindInfo.setLastUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
            mchntBindInfo.setUnBindDate(DateUtil.getCurrentDate());
            mchntBindInfo.setUnBindTime(DateUtil.getCurrentTime());
            iReturnCode = bspsMchntBindInfoMapper.updateBspsMchntBindInfoStatusByUserIdAndMchntNo(instId, mchntBindInfo);
            if (0 != iReturnCode && BspsAppParamConstant.NODATA_CODE != iReturnCode) {
                dbsUtil.dbsEndTransaction(false);
                rglog.error("收银员解绑失败,iReturnCode:<{}>", iReturnCode);
                throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
            }

            /*2-设备解绑（手机和语音设备）*/
            BspsDevBindInfoMapper bspsDevBindInfoMapper = new BspsDevBindInfoMapperImpl();
            DevBindInfo devBindInfo = new DevBindInfo();
            /*根法人行号+商户号+绑定人员id筛选数据*/
            devBindInfo.setInstId(instId);
            devBindInfo.setBindMchntNo(mchntNo);
            devBindInfo.setBindUserId(mchntBindInfo.getBindUserId());
            devBindInfo.setBindStatus(BindStatusEnum.UNBIND.getStatus());
            /*最后操作信息*/
            devBindInfo.setLastUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
            devBindInfo.setUnBindDate(DateUtil.getCurrentDate());
            devBindInfo.setUnBindTime(DateUtil.getCurrentTime());
            iReturnCode = bspsDevBindInfoMapper.updateBspsDevBindInfoStatusByUserIdAndMchntNo(instId, devBindInfo);
            if (0 != iReturnCode && BspsAppParamConstant.NODATA_CODE != iReturnCode) {
                dbsUtil.dbsEndTransaction(false);
                rglog.error("解绑收银员设备失败,iReturnCode:<{}>", iReturnCode);
                throw new BizException(RespCodeEnum.UNBIND_DEVBINDINFO_ERROR.getRespCode(), RespCodeEnum.UNBIND_DEVBINDINFO_ERROR.getRespDesc());
            }

            /*3-二维码信息解绑*/
            BspsQrCodeInfoMapper bspsQrCodeInfoMapper = new BspsQrCodeInfoMapperImpl();
            QrCodeInfo qrCodeInfo = new QrCodeInfo();
            /*根据法人行号，商户号，绑定人筛选解绑二维码数据*/
            qrCodeInfo.setInstId(instId);
            qrCodeInfo.setMchntNo(mchntNo);
            qrCodeInfo.setLogoUrlPath("");
            qrCodeInfo.setRemark3("");
            qrCodeInfo.setUserId(mchntBindInfo.getBindUserId());
            qrCodeInfo.setBindStatus("00");
            /*最后操作信息*/
            qrCodeInfo.setLastOprId(userId);
            qrCodeInfo.setLastUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
            iReturnCode = bspsQrCodeInfoMapper.updateBspsQrCodeInfoStatusByUserIdAndMchntNo(qrCodeInfo);
            if (0 != iReturnCode && BspsAppParamConstant.NODATA_CODE != iReturnCode) {
                rglog.error("二维码解绑失败,iReturnCode:<{}>", iReturnCode);
                throw new BizException(RespCodeEnum.UPDATE_QRCODE_INFO_ERROR.getRespCode(), RespCodeEnum.UPDATE_QRCODE_INFO_ERROR.getRespDesc());
            }
        }
        dbsUtil.dbsEndTransaction(true);

        /* 拼装响应结果 */
        BizResponse<MchntUnBindResponse> bizResponse = new BizResponse<>();
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(mchntUnBindResponse);
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        MchntUnBindResponse mchntUnBindResponse = (MchntUnBindResponse) bizResponse.getResult();
        ConvertUtil.convertInput(mchntUnBindResponse);
    }
}
